with sharing public class OverrideSubRegionBudgetNew
{
    public String msg{get;set;}
    public Boolean ForUpdate; // record for update 
    public Boolean Submitted; // submit flag
    public Boolean DisplaySave{get;set;} // display Save button or not
    public Boolean DisplaySubmit{get;set;}    
    String RegionName;
    
     public RegionalBudget__c RegionalBudget{
         get{
             if(RegionalBudget== null)
                 RegionalBudget= new RegionalBudget__c();
             return RegionalBudget;
         }
         set;
    }
       
    public Sub_Region_Budget__c SubRegionBudget{
         get{
             if(SubRegionBudget== null)
                 SubRegionBudget= new Sub_Region_Budget__c();
             return SubRegionBudget;
         }
         set;
    }
         
    
    public PE_Sample_Management__c PESM {
         get{
             if(PESM == null)
                 PESM = new PE_Sample_Management__c();
             return PESM ;
         }
         set;
    }      
        
    public List<TableItemControl> TableItemsDown{         
        get{
             if(TableItemsDown== null)
                 TableItemsDown= new List<TableItemControl>();
             return TableItemsDown;
         }
        set;
    }    
    
    public String UrlId
    {
        get{        
            return System.currentPageReference().getParameters().get('id');     
        }  
        set;
    }
    public String RegionalId
    {
        get{        
            return System.currentPageReference().getParameters().get('Rid');     
        }  
        set;
    }       
    User cu  = [Select Name,UserRoleId,Title__c From User Where Id =:UserInfo.getUserId()];
    UserRole ur = [Select Id,Name From UserRole Where Id =: cu.UserRoleId];
    Profile RGMProfile = [Select p.Name, p.Id From Profile p Where p.Name =: 'Regional General Manager'];

    public OverrideSubRegionBudgetNew(){    
        List<Place__c> pList = new  List<Place__c>();
        Submitted = true;
        ForUpdate = false;
        DisplaySave = true;
        DisplaySubmit = true;
        PESM = [Select id,Year__c,Rate__c,Deal__c,EOC_budget_allocation_kg__c,EOC_Total_budget_RMB__c,SOC_budget_allocation_kg__c,SOC_Total_budget_RMB__c  
                ,NOC_budget_allocation_kg__c,NOC_Total_budget_RMB__c,WOC_budget_allocation_kg__c,WOC_Total_budget_RMB__c 
                From PE_Sample_Management__c Where id =: UrlId];
                        
        RegionalBudget = [Select r.TotalBudgetRMB__c,  r.ThisYearKg_No__c, r.ThisYearKg_Kg__c, r.Submit__c, r.Region__c,
                 r.PESampleManagement__c, r.OwnerId, r.Over__c, r.Name, r.LastYearSalesWeighting__c, r.LastYearKg_No__c,
                 r.LastYearKg_Kg__c, r.LastYearConversionWeighting__c, r.Id,r.BudgetAllocationKg__c, 
                 r.Approved__c, r.ApprovalStatus__c From RegionalBudget__c r where r.id =: RegionalId];
                 

       if(!PESM.Deal__c) // not deal
       {
           msg = '样品管理未下发';
       }
       else
       {
           List<Sub_Region_Budget__c> ExistRecord = [Select s.total_score__c, s.potential_score__c,s.InMarketValueHide__c,s.ConversionForcast__c, 
                s.final_weighting__c, s.Year__c, s.Total_budget_kg__c, s.Total_budget_RMB__c, s.This_year_PE_Sample_kg__c, 
                s.This_year_In_market_sales_kg__c,  s.Submit__c, s.Sub_Region__c, s.Sales_City__c, s.Region__c,s.RegionalBudget__c, 
                s.Rate__c, s.Place__c, s.PE_Sample_Management__c, s.OwnerId, s.Name, s.Line_Manager__c, s.Last_year_sales_weighting__c,
                s.Last_year_conversion_weighting__c, s.Last_year_PE_Sample_kg__c, s.Last_year_In_market_sales_kg__c, s.IsDeleted, s.Id, s.Area__c,s.RMMM__c,
                s.Approved__c From Sub_Region_Budget__c s Where s.RegionalBudget__c =: RegionalId]; // select exist records
            
            if((ur.Name == 'WOC Regional General Manager')||(ur.Name == 'SOC Regional General Manager')||
                (ur.Name == 'NOC Regional General Manager')||(ur.Name == 'EOC Regional General Manager')){
                
                if(ExistRecord.size() <= 0){ // RGM select non records, so it doesn't submit
                    msg = '审批未提交';
                    Submitted = false;
                    DisplaySave = false;
                    DisplaySubmit = false;
                    
                }
                else{
                    if(RegionalBudget.Submit__c == false) // Records are not submitted
                    {
                        msg = '审批未提交';
                        Submitted = false;  
                        DisplaySave = false;
                        DisplaySubmit = false;       
                    }
                } 
                
            }
            
            SubRegionBudget.Year__c = PESM.Year__c;
            SubRegionBudget.Rate__c = PESM.Rate__c;
            
            // get place from current user's role
            if((ur.Name == 'MMKT:EOC-Senior Regional MMKT Mgr')||(ur.Name == 'EOC Regional General Manager'))
            {
                RegionName = '华东区';
                SubRegionBudget.Total_budget_kg__c = PESM.EOC_budget_allocation_kg__c;
                SubRegionBudget.Total_budget_RMB__c = PESM.EOC_Total_budget_RMB__c;
                pList = [Select id,name,Region__r.name From Place__c Where PlaceType__c = 'Sub-region' and  Region__r.Name =: '华东区'];
                                          
            }
            if((ur.Name == 'MMKT:NOC-Senior Regional MMKT Mgr')||(ur.Name == 'NOC Regional General Manager'))
            {
                RegionName = '华北区';
                SubRegionBudget.Total_budget_kg__c = PESM.NOC_budget_allocation_kg__c;
                SubRegionBudget.Total_budget_RMB__c = PESM.NOC_Total_budget_RMB__c;        
                pList = [Select id,name,Region__r.name From Place__c Where PlaceType__c = 'Sub-region' and  Region__r.Name =: '华北区'];                            
            }        
            if((ur.Name == 'MMKT:SOC-Senior Regional MMKT Mgr')||(ur.Name == 'SOC Regional General Manager'))
            {
                RegionName = '华南区';
                SubRegionBudget.Total_budget_kg__c = PESM.SOC_budget_allocation_kg__c;
                SubRegionBudget.Total_budget_RMB__c = PESM.SOC_Total_budget_RMB__c;        
                pList = [Select id,name,Region__r.name From Place__c Where PlaceType__c = 'Sub-region' and  Region__r.Name =: '华南区'];
               
            }
            if((ur.Name == 'MMKT:WOC-Senior Regional MMKT Mgr')||(ur.Name == 'WOC Regional General Manager'))
            {
                RegionName = '华西区';
                SubRegionBudget.Total_budget_kg__c = PESM.WOC_budget_allocation_kg__c;
                SubRegionBudget.Total_budget_RMB__c = PESM.WOC_Total_budget_RMB__c;        
                pList = [Select id,name,Region__r.name From Place__c Where PlaceType__c = 'Sub-region' and  Region__r.Name =: '华西区'];
               
            }

                // put place to page table

                Decimal TotalLastYearPEShipmentValue = 0;
                Decimal TotalLastYearPEConversionValue = 0;
                Decimal TotalThisYearPEConversionValue = 0;
                Decimal TotalLastYearInMarketSalesValue = 0;
                Decimal TotalThisYearInMarketSalesValue = 0;
                        
                List<InMarketSales__c> TotalLastYearInMarketSales = [Select InMarketSaleskg__c, SubRegion__c From 
                                       InMarketSales__c Where InMarketSaleskg__c > 0 and Year__c =: integer.valueof(SubRegionBudget.Year__c)-1 and Region__c =: RegionName ];                    
                
                for(InMarketSales__c t : TotalLastYearInMarketSales )
                {
                    TotalLastYearInMarketSalesValue += (Decimal)t.InMarketSaleskg__c;
                }
                List<InMarketSales__c> TotalThisYearInMarketSales = [Select InMarketSalesForcast__c,SubRegion__c From InMarketSales__c Where InMarketSalesForcast__c > 0 
                                                                    and Year__c =: integer.valueof(SubRegionBudget.Year__c) and Region__c =: RegionName];
                
                for(InMarketSales__c t : TotalThisYearInMarketSales )
                {
                    if((Decimal)t.InMarketSalesForcast__c > 0)
                        TotalThisYearInMarketSalesValue += (Decimal)t.InMarketSalesForcast__c;
                }
                
                List<AggregateResult> TotalLastYearPEConversion = [Select sum(PE_conversion_achieve__c)TotalIn  From 
                                      Achieve__c Where PE_conversion_achieve__c > 0 and   Year__c =: string.valueof(integer.valueof(SubRegionBudget.Year__c)-1) and  region__c =: RegionName ];                                
                List<AggregateResult> TotalThisYearPEConversion = [Select sum(PE_Conversion_forecast__c)TotalIn  From 
                                      Achieve__c Where PE_Conversion_forecast__c > 0 and   Year__c =: string.valueof(integer.valueof(SubRegionBudget.Year__c)) and  region__c =: RegionName ];  
                TotalLastYearPEConversionValue = (Decimal)TotalLastYearPEConversion[0].get('TotalIn');
                TotalThisYearPEConversionValue = (Decimal)TotalThisYearPEConversion[0].get('TotalIn');
                
                List<AggregateResult> TotalLastYearPEShipment = [Select sum(KG__c)TotalIn  From Shipment__c Where KG__c > 0 and   Year__c =: integer.valueof(SubRegionBudget.Year__c)-1 and Region__c =: RegionName and CalcInKg__c =: true];

                TotalLastYearPEShipmentValue = (Decimal)TotalLastYearPEShipment[0].get('TotalIn');
        
                for(Place__c p : pList)
                {
                    TableItemControl T = new TableItemControl();
                    T.Str = p.name;
                    Decimal SubRegionLastYearInMarketSalesValue = 0;
                    Decimal SubRegionThisYearInMarketSalesValue = 0;
                    for(InMarketSales__c tl : TotalLastYearInMarketSales )
                    {
                        if(p.name == tl.SubRegion__c)
                        {
                            SubRegionLastYearInMarketSalesValue += (Decimal)tl.InMarketSaleskg__c;
                        }
                    }
                    for(InMarketSales__c tl : TotalThisYearInMarketSales )
                    {
                        if(p.name == tl.SubRegion__c)
                        {
                            if((Decimal)tl.InMarketSalesForcast__c > 0)
                                SubRegionThisYearInMarketSalesValue += (Decimal)tl.InMarketSalesForcast__c;
                        }
                    }
                    if(TotalLastYearInMarketSalesValue > 0) 
                        T.SRB.Last_year_sales_weighting__c = SubRegionLastYearInMarketSalesValue / TotalLastYearInMarketSalesValue * 100;
                    else
                        T.SRB.Last_year_sales_weighting__c = 0;

        
                    List<AggregateResult> SubRegionLastYearPEConversion = [Select sum(PE_conversion_achieve__c)TotalIn  From 
                                          Achieve__c Where PE_conversion_achieve__c > 0 and   Year__c =: string.valueof(integer.valueof(SubRegionBudget.Year__c)-1) and subregion__c =: p.name];
                    List<AggregateResult> SubRegionThisYearPEConversion = [Select sum(PE_Conversion_forecast__c)TotalIn  From 
                                          Achieve__c Where PE_Conversion_forecast__c > 0 and   Year__c =: string.valueof(integer.valueof(SubRegionBudget.Year__c)) and subregion__c =: p.name];
                    if(TotalLastYearPEConversion.size() > 0){
                        if(((Decimal)TotalLastYearPEConversion[0].get('TotalIn') > 0)&&((Decimal)SubRegionLastYearPEConversion[0].get('TotalIn') > 0))
                            T.SRB.Last_year_conversion_weighting__c = (Decimal)SubRegionLastYearPEConversion[0].get('TotalIn') / (Decimal)TotalLastYearPEConversion[0].get('TotalIn') * 100;
                        else
                            T.SRB.Last_year_conversion_weighting__c = 0;
                    }
                    else
                    {
                        T.SRB.Last_year_conversion_weighting__c = 0;
                    }
                    
                    List<Shipment__c > SubRegionLastYearPEShipment = [Select KG__c,SubRegion__c From Shipment__c Where KG__c > 0 and   Year__c =: integer.valueof(SubRegionBudget.Year__c)-1 and SubRegion__c =:p.name and CalcInKg__c =: true];

                    Decimal LastYearPEShipmentValue = 0;

                    for(Shipment__c tl : SubRegionLastYearPEShipment )
                    {
                        LastYearPEShipmentValue += (Decimal)tl.KG__c;
                    }                    
 
                    
                    if(LastYearPEShipmentValue > 0)
                        T.SRB.Last_year_In_market_sales_kg__c = SubRegionLastYearInMarketSalesValue / LastYearPEShipmentValue;
                    else
                        T.SRB.Last_year_In_market_sales_kg__c = 0;
                    if((Decimal)SubRegionLastYearPEConversion[0].get('TotalIn')> 0)   
                        T.SRB.Last_year_PE_Sample_kg__c = LastYearPEShipmentValue / (Decimal)SubRegionLastYearPEConversion[0].get('TotalIn');
                    else
                        T.SRB.Last_year_PE_Sample_kg__c = 0;
                        
                    T.SRB.InMarketValueHide__c =  SubRegionThisYearInMarketSalesValue;
                    T.SRB.ConversionForcast__c =  (Decimal)SubRegionThisYearPEConversion[0].get('TotalIn');
                    T.SRB.This_year_In_market_sales_kg__c = 0;
                    T.SRB.This_year_PE_Sample_kg__c = 0;    
                                        
                    TableItemsDown.add(T);
                } 
                
                TableItemControl TT = new TableItemControl();
                TT.Str = '总计';
                TT.InputPercent = 100;
                TT.SRB.Last_year_sales_weighting__c = 100;
                TT.SRB.Last_year_conversion_weighting__c = 100; 
                
                if(TotalLastYearPEShipmentValue > 0) 
                    TT.SRB.Last_year_In_market_sales_kg__c = TotalLastYearInMarketSalesValue / TotalLastYearPEShipmentValue ;
                else
                    TT.SRB.Last_year_In_market_sales_kg__c = 0;
                if((TotalLastYearPEConversionValue > 0)&&(TotalLastYearPEShipmentValue > 0)) 
                    TT.SRB.Last_year_PE_Sample_kg__c = TotalLastYearPEShipmentValue / TotalLastYearPEConversionValue ;
                else
                    TT.SRB.Last_year_PE_Sample_kg__c = 0;
                
                
                TT.SRB.InMarketValueHide__c =  TotalThisYearInMarketSalesValue;
                TT.SRB.ConversionForcast__c =  TotalThisYearPEConversionValue;
                TT.SRB.This_year_In_market_sales_kg__c = 0;
                TT.SRB.This_year_PE_Sample_kg__c = 0;
                TT.SRB.RMMM__c = RegionalBudget.ownerid;       
           
                TableItemsDown.add(TT);

               if(ExistRecord.size() >0)
               {
                   if(RegionalBudget.ApprovalStatus__c == '审批通过')
                   {
                            msg = '审批通过，不能再修改！';
                            DisplaySave = false;
                            DisplaySubmit = false;        
                   }
                   if(RegionalBudget.ApprovalStatus__c == '等待大区经理审批')
                   {
                            msg = '已提交申请，不能再修改！';
                            DisplaySave = false;
                            DisplaySubmit = false;        
                   }                                    
                   // record exist, and submit is true. so can't change the record.
                   if((ur.Name == 'MMKT:WOC-Senior Regional MMKT Mgr')|| (ur.Name == 'MMKT:SOC-Senior Regional MMKT Mgr') 
                       ||(ur.Name == 'MMKT:NOC-Senior Regional MMKT Mgr') ||(ur.Name == 'MMKT:EOC-Senior Regional MMKT Mgr')){
                        if(RegionalBudget.Submit__c){ 
                            msg = '已提交申请，不能再修改！';
                            DisplaySave = false;
                            DisplaySubmit = false;             
                        }
                   }
                   ForUpdate = true;
                   for(Sub_Region_Budget__c er : ExistRecord)
                   {
                       for(TableItemControl tid : TableItemsDown)
                       {
                           if(er.name.contains(tid.Str))
                               tid.SRB = er;
                       }
                   }   
               } 
        }
        if(((ur.Name == 'WOC Regional General Manager')||(ur.Name == 'SOC Regional General Manager')||
        (ur.Name == 'NOC Regional General Manager')||(ur.Name == 'EOC Regional General Manager'))&&(DisplaySave == false))
        {
            TableItemsDown.clear();  
        }
    }

    public void SetRecord(Boolean Submit)
    {
        // update or insert the records from table items
        List<Sub_Region_Budget__c> SubRegionBudgetList = new List<Sub_Region_Budget__c>();
        List<Place__c> Region = [Select id From Place__c Where Name =: RegionName];
        for(TableItemControl t : TableItemsDown){
            if(t.SRB.Total_budget_kg__c == null)
            {
                t.SRB.Total_budget_kg__c = 0;
                t.SRB.Total_budget_RMB__c = 0;
            }
                
            if(T.Str == '总计')
            {
                continue;
            }
            User RGM = [Select id From User Where ProfileId =: RGMProfile.id and UserRegion__c =: RegionName];
            T.SRB.RGM__c = RGM.id;
            t.SRB.Year__c = SubRegionBudget.Year__c;
            t.SRB.RegionalBudget__c = RegionalId;
            t.SRB.Rate__c = SubRegionBudget.Rate__c;
            if(t.SRB.Total_budget_kg__c > 0)
                t.SRB.Total_budget_RMB__c = t.SRB.Total_budget_kg__c * SubRegionBudget.Rate__c;
            if(t.SRB.Total_budget_kg__c > 0)
                t.SRB.This_year_In_market_sales_kg__c = t.SRB.InMarketValueHide__c / t.SRB.Total_budget_kg__c;
            else
                t.SRB.This_year_In_market_sales_kg__c = 0;
            t.SRB.This_year_In_market_sales_kg__c = t.SRB.This_year_In_market_sales_kg__c.intValue();
            if(t.SRB.ConversionForcast__c > 0)
                t.SRB.This_year_PE_Sample_kg__c = t.SRB.Total_budget_kg__c / t.SRB.ConversionForcast__c;
            else
                 t.SRB.This_year_PE_Sample_kg__c = 0;
            t.SRB.This_year_PE_Sample_kg__c = t.SRB.This_year_PE_Sample_kg__c.intValue();
            
            t.SRB.Ownerid = t.SRB.RMMM__c;
            t.SRB.Submit__c = Submit;
            t.SRB.Name = SubRegionBudget.Year__c + '年' + t.str + '专业样品管理';
            if(!ForUpdate){
                t.SRB.PE_Sample_Management__c = UrlId;
            }
              
            SubRegionBudgetList.add(t.SRB);
        }
        if(ForUpdate)
        {
            if(SubRegionBudgetList.size() > 0)
                update SubRegionBudgetList;
                
            List<String> UpdateSubRegionIds = new List<String>();
            for(Sub_Region_Budget__c s : SubRegionBudgetList)
            {
                UpdateSubRegionIds.add(s.id);
            }
                
            List<Sub_regional_Monthly_Budget__c> DelSRMB = [Select id From Sub_regional_Monthly_Budget__c Where Sub_Region_Budget__c in: UpdateSubRegionIds];
            if(DelSRMB.size() > 0)
            {
                delete DelSRMB;
            }
            
            List<Sub_regional_Monthly_Budget__c> InsertSubMonBudget = new List<Sub_regional_Monthly_Budget__c>();
            for(Sub_Region_Budget__c sub : SubRegionBudgetList)
            {
                string IdSelect = sub.name.substring(sub.name.indexOf('年')+1,sub.name.indexOf('专'));
                List<AggregateResult> TotalLastYearInMarketSales = [Select sum(InMarketSaleskg__c)InMarketSales, Month__c Mon From 
                   InMarketSales__c Where InMarketSaleskg__c > 0 and Year__c =: Integer.valueof(PESM.Year__c)-1  and SubRegion__c =: IdSelect group by Month__c]; 
    
                List<AggregateResult> TotalThisYearInMarketSales = [Select sum(InMarketSalesForcast__c)InMarketSales, Month__c Mon From 
                   InMarketSales__c Where InMarketSalesForcast__c > 0 and Year__c =: Integer.valueof(PESM.Year__c) and SubRegion__c =: IdSelect group by Month__c];                 
    
                List<AggregateResult> TotalLastYearPEShipment = [Select sum(KG__c)kg,Month__c Mon From Shipment__c Where KG__c > 0 and   Year__c =: Integer.valueof(PESM.Year__c)-1 and SubRegion__c =: IdSelect and CalcInKg__c =: true group by Month__c];
    
                List<AggregateResult> SubRegionLastYearPEConversion = [Select sum(PE_conversion_achieve__c)TotalIn,Month__c Mon  From 
                                              Achieve__c Where PE_conversion_achieve__c > 0 and   Year__c =: string.valueof(Integer.valueof(PESM.Year__c)-1) and subregion__c =: IdSelect group by Month__c];
                
                List<AggregateResult> SubRegionThisYearPEConversion = [Select sum(PE_Conversion_forecast__c)TotalIn,Month__c Mon  From 
                                              Achieve__c Where PE_Conversion_forecast__c > 0 and   Year__c =: PESM.Year__c and subregion__c =: IdSelect group by Month__c];
    
                Decimal TotalLastYearPEShipmentValue = 0;
    
                Decimal TotalLastYearPEConversionValue = 0;
                Decimal TotalThisYearPEConversionValue = 0;
                Decimal TotalLastYearInMarketSalesValue = 0;
                Decimal TotalThisYearInMarketSalesValue = 0;

                Integer num;
                for(num = 1;num < 13;num++)
                {
                    Sub_regional_Monthly_Budget__c InsertSubMonItem = new Sub_regional_Monthly_Budget__c();
                    InsertSubMonItem.Budget_KG__c = 0;

                    InsertSubMonItem.Budget_RMB__c = InsertSubMonItem.Budget_KG__c * SubRegionBudget.Rate__c;
                    InsertSubMonItem.name = sub.name.replace('专业样品管理','') + string.valueof(num) + '月专业样品管理';
                    InsertSubMonItem.Sub_Region_Budget__c = sub.id;
                    InsertSubMonItem.Month__c = string.valueof(num);

                    InsertSubMonBudget.add(InsertSubMonItem);
                }     
            }
            try{
                insert InsertSubMonBudget; 
            }
            catch (DmlException e) {
                ApexPages.addMessages(e);
            } 
                
        }
        else
        {
            insert SubRegionBudgetList;
            ForUpdate = true;

            List<Sub_regional_Monthly_Budget__c> InsertSubMonBudget = new List<Sub_regional_Monthly_Budget__c>();
            for(Sub_Region_Budget__c sub : SubRegionBudgetList)
            {
                
                string IdSelect = sub.name.substring(sub.name.indexOf('年')+1,sub.name.indexOf('专'));
                List<AggregateResult> TotalLastYearInMarketSales = [Select sum(InMarketSaleskg__c)InMarketSales, Month__c Mon From 
                   InMarketSales__c Where InMarketSaleskg__c > 0 and Year__c =: Integer.valueof(PESM.Year__c)-1  and SubRegion__c =: IdSelect group by Month__c]; 
    
                List<AggregateResult> TotalThisYearInMarketSales = [Select sum(InMarketSalesForcast__c)InMarketSales, Month__c Mon From 
                   InMarketSales__c Where InMarketSalesForcast__c > 0 and Year__c =: Integer.valueof(PESM.Year__c) and SubRegion__c =: IdSelect group by Month__c];                 
    
                List<AggregateResult> TotalLastYearPEShipment = [Select sum(KG__c)kg,Month__c Mon From Shipment__c Where KG__c > 0 and   Year__c =: Integer.valueof(PESM.Year__c)-1 and SubRegion__c =: IdSelect group by Month__c];
    
                List<AggregateResult> SubRegionLastYearPEConversion = [Select sum(PE_conversion_achieve__c)TotalIn,Month__c Mon  From 
                                              Achieve__c Where PE_conversion_achieve__c > 0 and   Year__c =: string.valueof(Integer.valueof(PESM.Year__c)-1) and subregion__c =: IdSelect group by Month__c];
                
                List<AggregateResult> SubRegionThisYearPEConversion = [Select sum(PE_Conversion_forecast__c)TotalIn,Month__c Mon  From 
                                              Achieve__c Where PE_Conversion_forecast__c > 0 and   Year__c =: PESM.Year__c and subregion__c =: IdSelect group by Month__c];
    
                Decimal TotalLastYearPEShipmentValue = 0;
    
                Decimal TotalLastYearPEConversionValue = 0;
                Decimal TotalThisYearPEConversionValue = 0;
                Decimal TotalLastYearInMarketSalesValue = 0;
                Decimal TotalThisYearInMarketSalesValue = 0;

                Integer num;
                for(num = 1;num < 13;num++)
                {
                    Sub_regional_Monthly_Budget__c InsertSubMonItem = new Sub_regional_Monthly_Budget__c();
                    
                    InsertSubMonItem.Budget_KG__c = 0;   
                    InsertSubMonItem.Budget_RMB__c = InsertSubMonItem.Budget_KG__c * SubRegionBudget.Rate__c;
                    InsertSubMonItem.name = sub.name.replace('专业样品管理','') + string.valueof(num) + '月专业样品管理';
                    InsertSubMonItem.Sub_Region_Budget__c = sub.id;
                    InsertSubMonItem.Month__c = string.valueof(num);

                    InsertSubMonBudget.add(InsertSubMonItem);
                }     
            }
            try{
                insert InsertSubMonBudget; 
            }
            catch (DmlException e) {
                ApexPages.addMessages(e);
            }               
        }   
    }


    public  pageReference Save()
    {
        if(!PESM.Deal__c)
        {
            return null;
        }
        Decimal AllocatedNum;     
        
        for(TableItemControl t : TableItemsDown){
            if(T.Str == '总计')
            {
                continue;
            }
            if(T.SRB.RMMM__c == null)
            {
                msg = '有片区负责人未填写！';
                AllocatedNum  = Decimal.valueof(0);
                return null;
            }

            if((t.SRB.Total_budget_kg__c != null)&&(t.SRB.Total_budget_kg__c > 0)){
                if((AllocatedNum == null)||(AllocatedNum == 0))
                    AllocatedNum = t.SRB.Total_budget_kg__c;
                else
                    AllocatedNum += t.SRB.Total_budget_kg__c;
            }
            
        }       
           
        if(!Submitted)
        {
            return null;      
        }
        SetRecord(false);
            
        return null;          
    }

    public PageReference Submit()
    {
        if(!PESM.Deal__c)
        {
            pageReference pr = new pageReference('/'+ RegionalId);     
            pr.setredirect(true);      
            return pr;
        }
        Decimal AllocatedNum;     
        
        for(TableItemControl t : TableItemsDown){
            if(T.Str == '总计')
            {
                continue;
            }
            if(T.SRB.RMMM__c == null)
            {
                msg = '有片区负责人未填写！';
                AllocatedNum  = Decimal.valueof(0);
                return null;
            }

            if((t.SRB.Total_budget_kg__c != null)&&(t.SRB.Total_budget_kg__c > 0)){
                if((AllocatedNum == null)||(AllocatedNum == 0))
                    AllocatedNum = t.SRB.Total_budget_kg__c;
                else
                    AllocatedNum += t.SRB.Total_budget_kg__c;
            }
            
        }       
           
        if(!Submitted)
        {
            pageReference pr = new pageReference('/'+ RegionalId);     
            pr.setredirect(true);      
            return pr;        
        }
        SetRecord(true);
        
        RegionalBudget.ApprovalStatus__c = '等待大区经理审批';
        Update RegionalBudget;
        
         // trigger regional approval
       
        Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();   
        req1.setObjectId(RegionalBudget.id);
        Approval.ProcessResult result = Approval.process(req1);  
           
        pageReference pr = new pageReference('/'+ RegionalId);     
        pr.setredirect(true);      
        return pr;    
    }            
    public PageReference Cancel()
    {
        pageReference pr = new pageReference('/'+ RegionalId);     
        pr.setredirect(true);      
        return pr;
    }
    private final ApexPages.StandardController controller;
    
    static testMethod void OverrideViewTest()
    {
        Profile p  = [select id from profile where name = 'System Administrator'or name =: '系统管理员'];
        UserRole RoleWOCRGM = [Select Id,Name From UserRole Where Name =: GlobalProperties.RoleWOCRGM ];
        
        User u1 = new User (alias = 'standt', email = 'shuaicao@isoftstone.com', emailencodingkey='UTF-8', UserRoleId = RoleWOCRGM.id,
                lastname = 'Testing', languagelocalekey = 'en_US', localesidkey='en_US', Title__c = 'Sales Rep',profileid = p.id, 
                timezonesidkey = 'America/Los_Angeles', username='asdfdaa@testorg1.com');
        insert u1;
        
        System.runAs(u1) {
            PE_Sample_Management__c PE = new PE_Sample_Management__c();
            PE.WOC_Total_budget_RMB__c = 1;
            PE.Deal__c = true;
            PE.WOC_budget_allocation_kg__c = 2;
            PE.WOCInMarketValueHide__c = 0;
            PE.WOCConversionForcast__c = 0;                  
            PE.SOC_Total_budget_RMB__c = 0;
            PE.SOC_budget_allocation_kg__c = 0;
            PE.SOCInMarketValueHide__c = 0;
            PE.SOCConversionForcast__c = 0;                  
            PE.EOC_Total_budget_RMB__c = 0;
            PE.EOC_budget_allocation_kg__c = 0;
            PE.EOCInMarketValueHide__c = 0;
            PE.EOCConversionForcast__c = 0;            
            PE.NOC_Total_budget_RMB__c = 0;
            PE.NOC_budget_allocation_kg__c = 0;
            PE.NOCInMarketValueHide__c = 0;
            PE.NOCConversionForcast__c = 0;
            PE.Rate__c =2;
            PE.Total_Budget_Allocation_RMB__c = 1;
            insert PE;
            
            RegionalBudget__c RB = new RegionalBudget__c();
            RB.PESampleManagement__c = PE.id;
            insert RB;
            
            test.setCurrentPageReference(Page.OverrideSubRegionBudgetNew);
            System.currentPageReference().getParameters().put('id', PE.Id);       
            System.currentPageReference().getParameters().put('Rid', RB.Id);       
            
            OverrideSubRegionBudgetNew testCase = new OverrideSubRegionBudgetNew();

            testCase.Save();
            testCase.Cancel();
        
        }       
    }
 
}